/*
 * CodeUtil.java 
 * 创建于  2013-7-16
 * 
 * 版权所有@深圳市精彩无限数码科技有限公司
 */
package com.jcwx.game.socket.codex;

/**
 * @author Administrator 数据包加解密辅助类
 */
public class CodeUtil {
	public static final String KEY = "jcwx";

	public static boolean encode(byte[] szText, int iDataLen, String key, int iOffset) {
		boolean bRet = false;
		byte[] pDest = szText;
		String szKey = key;
		int iIndex = 0;
		int kIndex = 0;
		int iTextLen = iDataLen;
		int iKeyLen = szKey.length();
		int iKeySumValue = 0;
		do {
			if (szText == null || iTextLen <= 0 || szKey == null) {
				break;
			}

			for (iIndex = 0; iIndex < iKeyLen; iIndex++) {
				iKeySumValue += key.charAt(iIndex);
			}

			// 加密
			for (iIndex = 0, kIndex = 0; iIndex < iDataLen; iIndex++) {

				pDest[iIndex] = (byte) (pDest[iIndex] + iTextLen + iOffset);
				pDest[iIndex] = (byte) (pDest[iIndex] ^ key.charAt(kIndex));
				pDest[iIndex] = (byte) (pDest[iIndex] ^ iKeySumValue);
				// System.out.println(pDest[iIndex]);
				kIndex++;
				iTextLen--;
				if (kIndex >= iKeyLen) {
					kIndex = 0;
				}
			}
			bRet = true;
		} while (true);

		return bRet;
	}

	public static boolean decode(byte[] szText, int iDataLen, String key, int iOffset) {
		boolean bRet = false;
		byte[] pDest = szText;
		String szKey = key;
		int iIndex = 0;
		int kIndex = 0;
		int iTextLen = iDataLen;
		int iKeyLen = szKey.length();
		int iKeySumValue = 0;
		do {
			if (szText == null || iTextLen <= 0 || szKey == null) {
				break;
			}

			for (iIndex = 0; iIndex < iKeyLen; iIndex++) {
				iKeySumValue += szKey.charAt(iIndex);
			}

			// 解密
			for (iIndex = 0, kIndex = 0; iIndex < iDataLen; iIndex++) {
				pDest[iIndex] = (byte) (pDest[iIndex] ^ iKeySumValue);
				pDest[iIndex] = (byte) (pDest[iIndex] ^ key.charAt(kIndex));
				pDest[iIndex] = (byte) (pDest[iIndex] - iTextLen - iOffset);
				kIndex++;
				iTextLen--;
				if (kIndex >= iKeyLen) {
					kIndex = 0;
				}
			}
			bRet = true;
		} while (true);

		return bRet;
	}

}
